"use client";
import React from 'react';
import { Button, Card, InputNumber, Space, Table, Typography, message, Input, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { approveTaxonomy, buildTaxonomy, CategoryDict } from '../../../lib/api';

type RowItem = CategoryDict & { key: string; checked?: boolean; kwText?: string };

const Page: React.FC = () => {
  const [loading, setLoading] = React.useState(false);
  const [inserted, setInserted] = React.useState(0);
  const [sampleSize, setSampleSize] = React.useState<number | null>(200);
  const [rows, setRows] = React.useState<RowItem[]>([]);
  const [checkAll, setCheckAll] = React.useState(false);

  const onBuild = React.useCallback(async () => {
    setLoading(true);
    try {
      const res = await buildTaxonomy(sampleSize ?? undefined);
      setInserted(res.inserted || 0);
      const list: RowItem[] = (res.preview || []).map((x, i) => ({
        key: `${i}`,
        code: x.code || '',
        name: x.name || '',
        definition: x.definition || '',
        keywords: x.keywords || [],
        is_active: 1,
        kwText: (x.keywords || []).join(', '),
        checked: false,
      }));
      setRows(list);
      setCheckAll(false);
      message.success('归纳完成');
    } catch (e: any) {
      message.error(e?.message || '归纳失败');
    } finally {
      setLoading(false);
    }
  }, [sampleSize]);

  const updateRow = (key: string, patch: Partial<RowItem>) => {
    setRows((prev) => prev.map((r) => (r.key === key ? { ...r, ...patch } : r)));
  };

  const columns: ColumnsType<RowItem> = [
    {
      title: '选',
      dataIndex: 'checked',
      width: 64,
      render: (_v, record) => (
        <input
          type="checkbox"
          checked={!!record.checked}
          onChange={(e) => updateRow(record.key, { checked: e.target.checked })}
        />
      ),
    },
    {
      title: 'Code',
      dataIndex: 'code',
      width: 160,
      render: (_v, record) => (
        <Input
          value={record.code}
          onChange={(e) => updateRow(record.key, { code: e.target.value })}
          onBlur={(e) => updateRow(record.key, { code: (e.target.value || '').trim().toUpperCase() })}
        />
      ),
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 220,
      render: (_v, record) => (
        <Input value={record.name} onChange={(e) => updateRow(record.key, { name: e.target.value })} />
      ),
    },
    {
      title: '定义',
      dataIndex: 'definition',
      render: (_v, record) => (
        <Input.TextArea
          value={record.definition}
          rows={2}
          onChange={(e) => updateRow(record.key, { definition: e.target.value })}
        />
      ),
    },
    {
      title: '关键词（逗号分隔）',
      dataIndex: 'kwText',
      width: 320,
      render: (_v, record) => (
        <Input
          placeholder="示例: 延迟, 丢件"
          value={record.kwText}
          onChange={(e) => updateRow(record.key, { kwText: e.target.value })}
        />
      ),
    },
  ];

  const approveSelected = React.useCallback(async () => {
    const selected = rows
      .filter((r) => r.checked)
      .map((r) => ({
        code: (r.code || '').trim().toUpperCase(),
        name: (r.name || '').trim(),
        definition: (r.definition || '').trim(),
        keywords: (r.kwText || '')
          .split(',')
          .map((s) => s.trim())
          .filter(Boolean),
        is_active: 1,
      }))
      .filter((x) => x.code && x.name);
    if (selected.length === 0) {
      message.warning('未选择或数据不完整（code/name 不能为空）');
      return;
    }
    setLoading(true);
    try {
      await approveTaxonomy(selected);
      message.success('已入库');
    } catch (e: any) {
      message.error(e?.message || '提交失败');
    } finally {
      setLoading(false);
    }
  }, [rows]);

  const approveAll = React.useCallback(async () => {
    const all = rows
      .map((r) => ({
        code: (r.code || '').trim().toUpperCase(),
        name: (r.name || '').trim(),
        definition: (r.definition || '').trim(),
        keywords: (r.kwText || '')
          .split(',')
          .map((s) => s.trim())
          .filter(Boolean),
        is_active: 1,
      }))
      .filter((x) => x.code && x.name);
    if (all.length === 0) {
      message.warning('没有可提交的数据');
      return;
    }
    setLoading(true);
    try {
      await approveTaxonomy(all);
      message.success('已入库');
    } catch (e: any) {
      message.error(e?.message || '提交失败');
    } finally {
      setLoading(false);
    }
  }, [rows]);

  return (
    <Card title="类目归纳审核" bordered>
      <Space direction="vertical" style={{ width: '100%' }} size={12}>
        <Space wrap>
          <span>样本条数：</span>
          <InputNumber value={sampleSize as any} min={1} onChange={(v) => setSampleSize((v as number) ?? null)} />
          <Button type="primary" onClick={onBuild} loading={loading}>触发归纳（build）</Button>
          <Tag color="blue">已入库新增：{inserted}</Tag>
          <Tag>预览候选：{rows.length} 条</Tag>
        </Space>

        <Space>
          <label>
            <input
              type="checkbox"
              checked={checkAll}
              onChange={(e) => {
                const v = e.target.checked;
                setCheckAll(v);
                setRows((prev) => prev.map((r) => ({ ...r, checked: v })));
              }}
            /> 全选
          </label>
          <Button onClick={approveSelected} disabled={loading}>批准选中</Button>
          <Button type="primary" onClick={approveAll} disabled={loading}>批准全部</Button>
        </Space>

        <Table<RowItem>
          rowKey={(r) => r.key}
          dataSource={rows}
          columns={columns}
          pagination={{ pageSize: 10 }}
        />
      </Space>
    </Card>
  );
};

export default Page;

